package com.jch.dm1_immutable_object.demo;


import java.util.HashMap;
import java.util.Map;

// 角色 ImmutableObject,Manipulator
public final class TestManipulator {

    private static volatile TestManipulator instance = new TestManipulator();

    private final Map<String,TestImmutableObject> map = new HashMap<>();

    public TestManipulator(){
        // 初始化 map 内的信息
        map.put("key0",new TestImmutableObject("s-0",0));
        map.put("key1",new TestImmutableObject("s-1",1));
        map.put("key2",new TestImmutableObject("s-2",2));
    }

    public static TestManipulator getInstance(){
        return instance;
    }

    /**
     * 变更状态对象 并返回旧值
     * @param key key
     * @param newState 新state对象
     * @return oldState对象
     */
    public TestImmutableObject changeStateTo(String key, TestImmutableObject newState){
        TestImmutableObject oldState;
        oldState = this.map.replace(key,newState);
        return oldState;
    }

    // 获取单个不可变对象
    public TestImmutableObject getStateByKey(String key){
        return map.get(key);
    }

    // 更新自身
    public void setInstance(TestManipulator newInstance){
        instance = newInstance;
    }

    public Map<String,TestImmutableObject> getMap(){
        // 防御性复制
        Map<String,TestImmutableObject> m = new HashMap<>();
        for (String key:map.keySet()){
            m.put(key,new TestImmutableObject(getStateByKey(key).getStateStr(),getStateByKey(key).getStateInt()));
        }
        return m;
    }

}
